﻿using Core.Models;
using Gridify;
using Mapster;

namespace Core.Extensions;

public static class PagingExtensions
{
    public static PaginatedData<TD> ToPaginatedList<T, TD>(
        this Paging<T> paging,
        int currentPage,
        int pageSize
    )
    {
        ArgumentNullException.ThrowIfNull(paging);
        if (pageSize <= 0)
            throw new ArgumentException("Page size must be greater than 0", nameof(pageSize));
        if (currentPage < 1)
            throw new ArgumentException("Current page must be at least 1", nameof(currentPage));

        // 计算总页数
        int totalPages = (int)Math.Ceiling(paging.Count / (double)pageSize);

        // 构建 PaginatedData 实例
        return new PaginatedData<TD>(
            items: paging.Data.Adapt<IEnumerable<TD>>() ?? Enumerable.Empty<TD>(),
            total: paging.Count,
            pageIndex: currentPage,
            pageSize: pageSize
        );
    }

    public static PaginatedData<T> ToPaginatedList<T>(
        this Paging<T> paging,
        int currentPage,
        int pageSize
    )
    {
        ArgumentNullException.ThrowIfNull(paging);
        if (pageSize <= 0)
            throw new ArgumentException("Page size must be greater than 0", nameof(pageSize));
        if (currentPage < 1)
            throw new ArgumentException("Current page must be at least 1", nameof(currentPage));

        // 计算总页数
        int totalPages = (int)Math.Ceiling(paging.Count / (double)pageSize);

        // 构建 PaginatedData 实例
        return new PaginatedData<T>(
            items: paging.Data.Adapt<IEnumerable<T>>() ?? Enumerable.Empty<T>(),
            total: paging.Count,
            pageIndex: currentPage,
            pageSize: pageSize
        );
    }
}
